<template>
  <div class="JNPF-common-layout">
    <div class="JNPF-common-layout-center">
      <el-row class="JNPF-common-search-box" :gutter="16">
        <el-form @submit.native.prevent label-width="80px">
          <el-col :span="8">
             <el-form-item label="损溢日期">
              <el-date-picker
                v-model="alarmdate"
                type="daterange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"/>
              </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="单据编号"><el-input
                v-model="listQuery.fbillno"
                clearable
                class="filter-item"
                placeholder="请输入单据编号"
              /></el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="单据状态">
                <el-select
              v-model="listQuery.fbillstate"
              class="filter-item"
              clearable
              placeholder="请选择单据状态"
            >
              <el-option
                v-for="item in fbillstateOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
              </el-form-item>
          </el-col>
          <el-col :span="2">
            <el-form-item>
                <el-button type="primary" @click="handleFilter">查找</el-button>
            </el-form-item>
          </el-col>
        </el-form>
      </el-row>
      <div class="JNPF-common-layout-main JNPF-flex-main">
        <!-- 查询结果 -->
        <JNPF-table  v-loading="listLoading" :data="list" >
          <el-table-column width="80" align="center" label="操作" class-name="small-padding">
            <template slot-scope="scope">
              <el-button type="text" @click="handleUpdate(scope.row)">浏览</el-button>
            </template>
          </el-table-column>
          <el-table-column width="60" :index="indexMethod" align="center" label="序号" type="index" />
          <el-table-column width="200px" align="left" label="单据编号" prop="fbillno"/>
          <el-table-column width="120" :formatter="formatfmrkuser" align="left" label="损溢人员" prop="fmrkuser" />
          <el-table-column width="100" :formatter="datetimeFormat" align="left" label="损溢日期" prop="fmrkdate" />
          <el-table-column align="center" label="品项数" prop="fitemcount" />
          <el-table-column align="center" label="总件数" prop="fpiececount" />
          <el-table-column align="left" label="单据状态" prop="fbillstate" >
            <template slot-scope="scope">
              <span
                :style="{color:buttonColor.itemisconfirmed}"
                v-if="scope.row.fbillstate === 1"
                >{{ scope.row.fbillstate | statusFilter }}</span
              >
              <span :style="{color:buttonColor.itemconfirmed}" v-else-if="scope.row.fbillstate === 2">{{
                scope.row.fbillstate | statusFilter
              }}</span>
              <span :style="{color:buttonColor.iteminvalid}" v-else>{{
                scope.row.fbillstate | statusFilter
              }}</span>
            </template>
          </el-table-column>
        </JNPF-table>
        <paginations
        :total="total"
        :page.sync="listQuery.currentPage"
        :limit.sync="listQuery.pageSize"
        />
      </div>
    </div>
    <el-dialog 
       :close-on-click-modal="false" 
       :before-close="handleClose" 
        :fullscreen="true"
        :title="textMap[dialogStatus]" 
       :visible.sync="dialogFormVisible"
      >
      <el-tabs type="border-card">
        <el-tab-pane label="头表" :style="{height:screenHeight-230+'px'}">
          <el-row class="JNPF-common-search-box" :gutter="16">
            <el-form @submit.native.prevent label-width="80px">
              <el-col :span="6">
                 <el-form-item class="required" label="单据编号" prop="fbillno">
                  <el-input disabled v-model="dataForm.fbillno"/>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item class="required" label="损溢日期" prop="fmrkdate">
                  <el-date-picker disabled v-model="dataForm.fmrkdate" type="date" />
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item class="required" label="单据状态" prop="fbillstate">
                    <el-select
                      disabled
                      v-model="dataForm.fbillstate"
                      class="filter-item"
                      clearable
                      placeholder="请选择单据状态"
                    >
                      <el-option
                        v-for="item in fbillstateOptions"
                        :key="item.value"
                        :label="item.label"
                        :value="item.value"
                      />
                </el-select>
              </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item class="required" label="损溢人员" prop="fmrkuser">
                  <el-select disabled  clearable filterable v-model="dataForm.fmrkuser" class="filter-item" placeholder="请选择损溢人员">
                      <el-option
                      v-for="item in getListfmrkuser"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"/>
                    </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item class="text"  label="备注" prop="fexplanation">
          <el-input disabled v-model="dataForm.fexplanation"/>
        </el-form-item>
              </el-col>
            </el-form>
          </el-row>
        </el-tab-pane>
        <el-tab-pane label="明细表">
          <!-- 查询结果 -->
              <JNPF-table :height="screenHeight-230"  v-loading="listLoading" :data="dataForm.details">
                <el-table-column align="center" label="行号" prop="fline" width="60px"/>
                <el-table-column align="left" label="容器标签" prop="frfidbarcode" width="240px"/>
                <el-table-column align="left" label="物料编号" prop="fgoodno" width="110px"/>
                <el-table-column :formatter="formatfgoodno" align="left" label="物料名称" prop="fgoodname" width="120px"/>
                <el-table-column :formatter="formatfspec" align="left" label="规格" prop="fspec" width="150px"/>
                <el-table-column :formatter="formatfunit" align="left" label="单位" prop="funit" width="60px"/>
                <el-table-column align="center" label="重量" prop="fqty" width="70px"/>
                <el-table-column :formatter="formatfboxbarcode" align="left" label="储物仓" prop="fboxbarcode"/>
                <el-table-column :formatter="formatfcabbarcode" align="left" label="储物柜" prop="fcabbarcode"/>
                <el-table-column width="100" :formatter="datetimeFormat" align="left" label="生产日期" prop="fprocdate" />
              </JNPF-table>
        </el-tab-pane>
      </el-tabs>
      <span slot="footer" class="dialog-footer">
        <div>
          <el-button type="info" @click="cancel()">取消</el-button>
        </div>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import { listmrkHead, createmrkHead, updatemrkHead, deletemrkHead } from '@/api/tcMrkHead'
import { listtsWarehouse } from '@/api/tsWarehouse'
import { listgoodInfo } from '@/api/goodInfo'
import { listtsCabinet } from '@/api/tsCabinet'
import moment from 'moment'
import { tableColor,titleColor,buttonColor } from '@/filters/index'
import { getListArea, getFbillno, checkBiz } from '@/api/area'

const statusMap = {
  1: '未损溢',
  2: '已损溢',
  8: '已作废'
}

export default {
  name: 'ITcMrkHead',
  filters: {
    statusFilter(type) {
      return statusMap[type]
    }
  },
  data() {
    return {
      screenHeight: document.body.clientHeight,
      panelHeight: 0,
      cabDialogFsiteNo: null,
      wareDialogFsiteNo: null,
      buttonColor:buttonColor,
      viewFlag:false,
      listCabinet:[],
      cabinetVisible:false,
      listgoodInfo: [],
      listWarehouse: [],
      warehouseVisible: false,
      materialIdVisible: false,
      materialFsiteNo: null,
      userFlag:null,
      searchVisibleuse: false,
      userDialogFsiteNo:null,
      dialogFormVisible1: false,
      dialogStatus1: null,
      detailsTmp: [],
      listTmp: [],
      dataForm1: {
        fline: undefined,
        fgoodno: undefined,
        fgoodname: undefined,
        frfidbarcode: undefined,
        fspec: undefined,
        funit: undefined,
        fqty: undefined,
        fboxbarcode: undefined,
        fboxbarcodeName: undefined,
        fcabbarcode: undefined,
        fcabbarcodeName: undefined,
        fprocdate: undefined,
      },
      flineList:[],
      selectList:[],

      getListfmrkuser: [],
      list: null,
      total: 0,
      listLoading: true,
      alarmdate: null,
      listQuery: {
        page: 1,
        limit: 20,
        fsiteNo: this.$store.state.user.fsiteNo,
        fmrkuser: undefined,
        fmrkdate: undefined,
        ftakedateStart: undefined,
        ftakedateEnd: undefined,
        fstockno: undefined,
        fitemcount: undefined,
        fpiececount: undefined,
        ftotalamt: undefined,
        fexplanation: undefined,
        fupddate: undefined,
        foperator: undefined,
        fcheckdate: undefined,
        fcheckuser: undefined,
        fbillstate: undefined,
        fbilltype: 2,
        sort: 'create_time',
        order: 'desc'
      },
      dataForm: {
        fsiteNo: undefined,
        fmrkuser: undefined,
        fmrkdate: undefined,
        fstockno: undefined,
        fitemcount: undefined,
        fpiececount: undefined,
        ftotalamt: undefined,
        fexplanation: undefined,
        fupddate: undefined,
        foperator: undefined,
        fcheckdate: undefined,
        fcheckuser: undefined,
        fbillstate: undefined,
        fbilltype: 2,
        id: undefined,
        details: []
      },
      tableColor: tableColor,
      titleColor: titleColor,
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: '编辑',
        create: '创建'
      },
      rules: {
        fbillno: [
          { required: true, message: '单据编号不能为空', trigger:'blur'},
        ],
        fsiteNo: [
          { required: true, message: '客户名称不能为空' },
        ],
        fmrkuser: [
          { required: true, message: '损溢人员不能为空' },
        ],
        fmrkdate: [
          { required: true, message: '损溢日期不能为空' },
        ],
        fstockno: [],
        fitemcount: [
          { type: 'number', message: '品项数必须为数字值' },
        ],
        fpiececount: [
          { type: 'number', message: '总件数必须为数字值' },
        ],
        ftotalamt: [],
        fexplanation: [],
        fupddate: [],
        foperator: [],
        fcheckdate: [],
        fcheckuser: [],
        fbillstate: [
          { type: 'number', message: '单据状态必须为数字值' },
        ],
        fbilltype: [
          { type: 'number', message: '损溢类型必须为数字值' },
        ],
      },
      rules1: {
        fline: [
          { required: true, message: '行号不能为空' },
          { type: 'number', message: '行号必须为数字值' },
        ],
        frfidbarcode: [
          { required: true, message: '容器标签不能为空' },
        ],
        fgoodno: [
          { required: true, message: '物料编号不能为空' },
        ],
        fbuyprice: [
          { required: true, message: '采购价不能为空' },
        ],
        fqty: [
          { required: true, message: '重量不能为空' },
        ],
        ftotamt: [
          { required: true, message: '合计不能为空' },
        ],
        fboxbarcode: [
          { required: true, message: '储物仓不能为空' },
        ],
        fcabbarcode: [
          { required: true, message: '储物柜不能为空' },
        ],
      },
      fbillstateOptions: [
        { value: 1, label: '未损溢' },
        { value: 2, label: '已损溢' },
        { value: 8, label: '已作废' },
      ]
    }
  },
  created() {
    this.panelHeight = document.documentElement.clientHeight-294
    this.alarmdate = [new Date(), new Date()]
    this.getList()
    // 人员弹出框
      getListArea({flag:13,arg1:this.$store.state.user.fsiteNo})
      .then(response => {
        this.getListfmrkuser = response.data.data.list
      })
      .catch(() => {
        this.getListfmrkuser = []
      })
      // 物料列表
      listgoodInfo({limit:-1,fsiteNo:this.$store.state.user.fsiteNo})
      .then(response => {
        this.listgoodInfo = response.data.data.list
      })
      .catch(() => {
        this.listgoodInfo = []
      })
      // 储物仓列表
      listtsWarehouse({limit:-1})
        .then(response => {
          this.listWarehouse = response.data.data.list
        })
        .catch(() => {
          this.listWarehouse = []
        })
        // 储物柜列表
        listtsCabinet({limit:-1})
        .then(response => {
          this.listCabinet = response.data.data.list
        })
        .catch(() => {
          this.listCabinet = []
        })
  },
  methods: {
    parserDate(date) {
      var t = Date.parse(date)
      if (!isNaN(t)) {
        return new Date(Date.parse(date.replace(/-/g, '/')))
      }
    },
    datetimeFormat(row, column) {
      const date = row[column.property]
      if (date === undefined || date === null) {
        return ''
      }
      return moment(date).format('YYYY-MM-DD')
    },
    formatDate: function(date) {
      if(typeof(date)==='object'){
         var ym
      var y = date.getFullYear()
      var m = date.getMonth() + 1
      var d = date.getDate()
      if (m < 10) {
        m = '0' + m
      }
      if (d < 10) {
        d = '0' + d
      }
      ym = '' + y + m + d
      return ym
      }else{
        return date
      }
    },
    // 储物仓名称
    formatfboxbarcode: function(row, column) {
      if(this.listWarehouse){
        for (let i = 0; i < this.listWarehouse.length; i++) {
          if (row.fboxbarcode == this.listWarehouse[i].fequipmentbarcode) {
            return this.listWarehouse[i].fequipmenttag
          }
        }
        return ''
      }else{
        return ''
      }
    },
      // 储物仓弹出框
    searchDialogwarehouse() {
      this.warehouseVisible = true
      this.wareDialogFsiteNo = this.dataForm.fsiteNo
    },

    // 储物仓弹出框
    warehouseDialogValue(value){
        this.dataForm1.fboxbarcode = value.info.fequipmentbarcode
        this.dataForm1.fboxbarcodeName = value.info.fequipmenttag
    },

    // 储物柜名称
    formatfcabbarcode: function(row, column) {
      if(this.listCabinet){
        for (let i = 0; i < this.listCabinet.length; i++) {
          if (row.fcabbarcode == this.listCabinet[i].fequipmentbarcode) {
            return this.listCabinet[i].fequipmenttag
          }
        }
        return ''
      }else{
        return ''
      }
    },

     // 储物柜弹出框
    searchDialogcabinet() {
      this.cabinetVisible = true
      this.cabDialogFsiteNo = this.dataForm.fsiteNo
    },

    // 储物柜弹出框
    cabinetDialogValue(value){
        this.dataForm1.fcabbarcode = value.info.fequipmentbarcode
        this.dataForm1.fcabbarcodeName = value.info.fequipmenttag
    },
     // 物料名称
    formatfgoodno: function(row, column) {
      if(this.listgoodInfo){
        for (let i = 0; i < this.listgoodInfo.length; i++) {
          if (row.fgoodno == this.listgoodInfo[i].fgoodno) {
            return this.listgoodInfo[i].fgoodname
          }
        }
        return ''
      }else{
        return ''
      }
    },
     // 物料规格
    formatfspec: function(row, column) {
      if(this.listgoodInfo){
        for (let i = 0; i < this.listgoodInfo.length; i++) {
          if (row.fgoodno == this.listgoodInfo[i].fgoodno) {
            return this.listgoodInfo[i].fspec
          }
        }
        return ''
      }else{
        return ''
      }
    },
     // 物料单位
    formatfunit: function(row, column) {
      if(this.listgoodInfo){
        for (let i = 0; i < this.listgoodInfo.length; i++) {
          if (row.fgoodno == this.listgoodInfo[i].fgoodno) {
            return this.listgoodInfo[i].funit
          }
        }
        return ''
      }else{
        return ''
      }
    },
    // 物料弹出框
    searchDialogMaterial() {
      this.materialIdVisible = true
      this.materialFsiteNo = this.dataForm.fsiteNo
    },

    // 物料弹出框
    materialDialogValue(value){
        this.dataForm1.fgoodno = value.data.fgoodno
        this.dataForm1.fgoodname = value.data.fgoodname
        this.dataForm1.fspec = value.data.fspec
        this.dataForm1.funit = value.data.funit
    },
    // 搜索人员弹出框
    searchDialoguse(value) {
      this.userFlag = value
      if(value === 'add'){
        this.userDialogFsiteNo = this.dataForm.fsiteNo
      }else{
        this.userDialogFsiteNo = this.listQuery.fsiteNo
      }
      this.searchVisibleuse = true
    },

    // 人员弹出框返回值
    userDialogValue(value){
      if(this.userFlag==='add'){
        this.dataForm.fmrkuser = value.user.id.toString()
      }else{
        this.listQuery.fmrkuser = value.user.id.toString()
      }
    },
    // 人员
    formatfmrkuser: function(row, column) {
      if(this.getListfmrkuser){
        for (let i = 0; i < this.getListfmrkuser.length; i++) {
        if (row.fmrkuser == this.getListfmrkuser[i].value) {
          return this.getListfmrkuser[i].label
        }
      }
      return ''
      }else{
      return ''
      }
    },
    getList() {
      this.listQuery.ftakedateStart = this.alarmdate == null ? null : this.formatDate(this.alarmdate[0])
      this.listQuery.ftakedateEnd = this.alarmdate == null ? null : this.formatDate(this.alarmdate[1])
      this.listLoading = true
      listmrkHead(this.listQuery)
        .then(response => {
          this.list = response.data.data.list
          this.total = response.data.data.total
          this.listLoading = false
        })
        .catch(() => {
          this.list = []
          this.total = 0
          this.listLoading = false
        })
    },
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    resetForm() {
      this.dataForm = {
        fsiteNo: undefined,
        fmrkuser: undefined,
        fmrkdate: undefined,
        fstockno: undefined,
        fitemcount: undefined,
        fpiececount: undefined,
        ftotalamt: undefined,
        fexplanation: undefined,
        fupddate: undefined,
        foperator: undefined,
        fcheckdate: undefined,
        fcheckuser: undefined,
        fbillstate: undefined,
        fbilltype: 2,
        id: undefined,
        details: []
      }
    },
    handleCreate() {
      this.resetForm()
       // 单据编号
      getFbillno({ flag: 2023 })
        .then((response) => {
          if (response) {
            this.dataForm.fbillno = response.data.data
            this.dialogFormVisible = true
            this.$nextTick(() => {
            this.$refs['dataForm'].clearValidate()
          })
          }
        })
        .catch(() => {
          this.dataForm.fbillno = ''
        })
        this.dataForm.fbillstate=1
        this.dataForm.fmrkdate = new Date()
        this.dataForm.fsiteNo = this.$store.state.user.fsiteNo;
        this.dataForm.fmrkuser = this.$store.state.user.id.toString()
      this.dialogStatus = 'create'
    },
    createData() {
      this.$refs['dataForm'].validate(valid => {
        if (valid) {
          createmrkHead(this.dataForm)
            .then(response => {
              this.list.unshift(response.data.data)
              this.dialogFormVisible = false
              this.$notify.success({
                title: '成功',
                message: '添加物料损溢主表成功'
              })
              this.selectList=[]
              this.flineList=[]
            })
            .catch(response => {
              this.$notify.error({
                title: '失败',
                message: response.data.data
              })
            })
        }
      })
    },
    handleUpdate(row) {
      if(row.fbillstate=='1'){
         this.viewFlag = false
      }else{
         this.viewFlag = true
      }
      this.dataForm = Object.assign({}, row)
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.detailsTmp = [];
      this.listTmp = row;
      row.details.forEach((v) => {
        this.detailsTmp.push(v);
        this.selectList.push(v.fgoodno)
        this.flineList.push(v.fline)
      });
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    audit(row) {
      this.$confirm('是否确定', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.dataForm = Object.assign({}, row)
        checkBiz({ pBillNo: this.dataForm.fbillno ,pBillState:2 ,pBizType: 'i_tc_mrk_head', pUser:this.$store.state.user.id })
            .then(() => {
              for (const v of this.list) {
                if (v.fbillno === this.dataForm.fbillno) {
                  this.dataForm.fbillstate = 2
                  const index = this.list.indexOf(v)
                  this.list.splice(index, 1, this.dataForm)
                  break
                }
              }
              this.$notify.success({
                title: '成功',
                message: '确认成功'
              })
            })
            .catch((response) => {
              this.$notify.error({
                title: '失败',
                message: response.data.data
              })
            })
      })
    },
    updateData() {
      this.$refs['dataForm'].validate(valid => {
        if (valid) {
          updatemrkHead(this.dataForm, this.$route.query.id)
            .then(() => {
              for (const v of this.list) {
                if (v.fbillno === this.dataForm.fbillno) {
                  const index = this.list.indexOf(v)
                  this.list.splice(index, 1, this.dataForm)
                  break
                }
              }
              this.dialogFormVisible = false
              this.$notify.success({
                title: '成功',
                message: '更新物料损溢主表成功'
              })
              this.selectList=[]
              this.flineList=[]
            })
            .catch(response => {
              this.$notify.error({
                title: '失败',
                message: response.data.data
              })
            })
        }
      })
    },
    handleDelete(row) {
      this.$confirm('是否要删除物料损溢主表', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deletemrkHead(row)
          .then(response => {
            this.$notify.success({
              title: '成功',
              message: '删除物料损溢主表成功'
            })
            const index = this.list.indexOf(row)
            this.list.splice(index, 1)
          })
          .catch(response => {
            this.$notify.error({
              title: '失败',
              message: response.data.data
            })
          })
      })
    },
    addData() {
      this.$refs['dataForm1'].validate((valid) => {
         // 判断行号是否重复
       const flinetem = this.flineList.indexOf(this.dataForm1.fline)
       // 判断物料id是否重复
       const tem = this.selectList.indexOf(this.dataForm1.fgoodno)
       if(flinetem<0){
          if(tem<0){
          if (valid) {
          this.dialogFormVisible1 = false
          this.dataForm.details.push(this.dataForm1)
          this.selectList.push(this.dataForm1.fgoodno)
          this.flineList.push(this.dataForm1.fline)
          }
        }else{
          this.$notify.error({
                title: '失败',
                message: '所选物料重复'
              })
          return;
        }
       }else{
         this.$notify.error({
              title: '失败',
              message: '行号重复'
            })
         return;
       }
      })

    },

    cancel() {
      this.dialogFormVisible = false
      this.selectList=[]
      this.flineList=[]
      this.list.forEach((v) => {
        if (v.fbillno === this.dataForm.fbillno) {
          this.dataForm = this.listTmp
          this.dataForm.details = this.detailsTmp
          const index = this.list.indexOf(v)
          this.list.splice(index, 1, this.dataForm)
          return
        }
      })
    },

    // 弹窗点击关闭前的回调
      handleClose(){
        this.dialogFormVisible = false
        this.selectList=[]
      this.flineList=[]
        this.list.forEach((v) => {
          if (v.fbillno === this.dataForm.fbillno) {
            this.dataForm = this.listTmp
            this.dataForm.details = this.detailsTmp
            const index = this.list.indexOf(v)
            this.list.splice(index, 1, this.dataForm)
            return
          }
        })
      },

      handleUpdate1() {
      this.dialogStatus1 = "update";
      this.dialogFormVisible1 = true;
      this.dataForm1 = {
        fline: undefined,
        fgoodno: undefined,
        fgoodname: undefined,
        frfidbarcode: undefined,
        fspec: undefined,
        funit: undefined,
        fqty: undefined,
        fboxbarcode: undefined,
        fboxbarcodeName: undefined,
        fcabbarcode: undefined,
        fcabbarcodeName: undefined,
        fprocdate: undefined,
      };
      this.dataForm1.fprocdate = new Date()
      this.$nextTick(() => {
        this.$refs["dataForm1"].clearValidate();
      });
    },

     handleDelete1(row) {
       this.$confirm('是否要删除物料', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
          const index = this.dataForm.details.indexOf(row);
          this.dataForm.details.splice(index, 1);
          this.selectList.splice(index,1)
          this.flineList.splice(index,1)
      })

    },
    indexMethod(index) {
      index = index + 1
      return index
    }
  }
}
</script>